<?php
namespace Mob\Model;

use Think\Model;
use Think\Hook;
use Think\Model\AdvModel;
/**红包模型
 * Class InfoModel
 */
require_once('./Application/Mob/Common/function.php');
class RedPackModel extends AdvModel
{
	protected $tableName = 'payment';  //指定默认表名

   public function  creatorRedPack($Uid,$amount,$peopleNum,$allotMode='2',$businessid,$orderId,$wishing='',$remark='')
   {


	 $RedPack['paySerialno']=getPaySerialno();  //获取流水号
	 $RedPack['releaseUid']=$Uid;   ///发布人ID
     $RedPack['amount']=$amount;   //金额
	 $RedPack['balance']=$amount; //默认金额
     $RedPack['paymenttype']=1;  //类型为红包
	 $RedPack['peopleNum']=$peopleNum;  //人数
     $RedPack['allotMode']=$allotMode;  //分配模式
     $RedPack['wishing']=$wishing;
     $RedPack['remark']=$remark;
     $RedPack['orderId']=$orderId;
     $RedPack['activityId']=$businessid;
     if($this->add($RedPack))
     {
     return $RedPack['paySerialno'];

     }else
     {
     	return null;
     }

   }

     /**
	 * queryRedPack  查询红包
	 */

   public function queryRedPack($PaySerialno)
   {
   	$where['paySerialno']=$PaySerialno;
   	$where['paymenttype']=1;

   	return $this->where($where)->field('releaseUid,creationtime,releasestatus,Paystatus,releasetime,completetime,orderId,amount,balance,peopleNum,Currentpeople,businessid,wishing,remark,allotMode,activityId')->find();
   }
   public function payComplete($PaySerialno)
   {
   	$where['paySerialno']=$PaySerialno;
   	$where['payStatus']= array('IN','0,2');
   	$data['payTime']=getDateTime();
   	$data['payStatus']=1;
   	$data['releaseStatus']=1;
   	$this->where($where)->save($data);
   	$this->initializePedPack($PaySerialno);

   }

     /**
	 * updateOrderId  更新红包关联订单信息
	 */
  public function updateOrderId($paySerialno,$orderId)
  {
    $data= array('orderId'=>$orderId);
    $this->where(" paySerialno = '%s' ",$paySerialno)->save($data);


  }

     /**
	 * updateOrderId  更新红包关联订单信息
	 */
  public function abatementBalance($paySerialno,$moeny)
  {
   $where = array('paySerialno'=>$paySerialno,'releaseStatus'=>'1','payStatus'=>'1');
  $this->startTrans();  //开启事物
  $res= $this->where($where)->setDec('balance',$moeny);
 // $this->where($where)->setDec('balance',$moeny);
  $this->where($where)->setInc('Currentpeople');
 if($res)
 {
 $this->commit();
 }else
 {
  $this->rollback();
  }
  }



  /**
	 * isAcquire  红包是否可以发放
	 */

  public function isAcquire($paySerialno)
  {
  $where = array('paySerialno'=>$paySerialno,'releaseStatus'=>'1','payStatus'=>'1');
 $redpack = $this->where($where)->field('amount,balance')->find();

  if($redpack)
  {

   if($redpack['balance']>0)
   {

   	return true;
   }else
   {
   return false;
   }

  }else
  {
  return false;
  }


  }

     /**
	 * isEligibility  是否有红包申领条件
	 */

  public function isEligibility($paySerialno,$Uid)
  {

   $redpack =$this->queryRedPack($paySerialno);

   if(get_uid()==$redpack['releaseUid']) //如果领取人为发布人，则不能领取，返回。
   {
   return false;
   }

   if(!$redpack)
   {
   	return false;
   }

   $activity  = D('Activity')->queryActivity($redpack['activityId']);

   $activityType=$activity['activityType'];
   $businessId =$activity ['businessId'];

   switch($activityType)
   {
   	case 1:

   $notice = D('Notice');
   $res = $notice->isFirstBrowse($businessId,$Uid);
   if($res)
   {
   	return false;
   }
   return true;

   	break;

   	case 2:
   	break;

   	case 3:
   	break;

   	case 4:
   	break;


   }

  }

       /**
	 * allocatioNstrategy  红包策略
	 * @param $paySerialno  红包ID
	 * @param $total  总金额
	 * @param $number  红包个数
	 * @param $Type  分配方式，1=全部分配给第一个人，2=随机金额，3=固定金额
	 * @param $Acceptlongitude  纬度
	 * @return bool
	 * @author:wanghongyan
	 */


  private  function allocatioNstrategy($paySerialno, $total,$number,$Type,$minMeny=100,$maxMeny=200,$probability=30 )
  {

  	if($Type==1) //全部分配
  	{
  	$data['paySerialno']=$paySerialno;
  	$data['moeny']=	$total;
    $data['serial']=rand(1,100/$probability);  //为几率值
    $data['paymenttype']=1;
    $data['type']=1;
    $data['redPackSerialno']=getRedPackSerialno();

  	}elseif($Type==2) //随机金额
  	{

  	$place = unique_rand($probability,$number);
  	$avg = $total/$number;
  	for($count=0;$count<$number;$count++)
  	{
  	 $safe_total=($total-($number-$count)*$minMeny)/($number-$count);//随机安全上限
  	 if($safe_total<$minMeny)
  	 {
  	 $safe_total=	$avg;
  	 }
     if($count+1>=$number)
     {
     $money=$total;
     }else
     {
     $money=mt_rand($minMeny,$safe_total);
      $total=$total-$money;
     }
  //print_r("<p>第".($count+1)."次，总额为".$total."本次为:".$money);
 //    print_r("剩余为".$total."</p>");


  	$data[$count] = array('paySerialno'=>$paySerialno,
  	                      'moeny'=>$money,
  	                      'serial'=>$place[$count],
  	                      'paymenttype'>=1,
  	                      'type'=>2,
  	                      'redPackSerialno'=>getRedPackSerialno(),
  	                   );

  	}

  	}elseif($Type==3) //固定金额
  	{
  	$place = unique_rand($probability,$number);
  	$moeny = $total/$number;

  	for($count=0;$count<$number;$count++)
  	{
  	$data[$count] = array('paySerialno'=>$paySerialno,
  	                      'moeny'=>$moeny,
  	                      'serial'=>$place[$count],
  	                      'paymenttype'>=1,
  	                      'type'=>3,
  	                      'redPackSerialno'=>getRedPackSerialno(),
  	                   );
  	  }
  	}

   M('payment_list')->addAll($data);
     // return $data;
  }
  private function initializePedPack($paySerialno)
  {
  $RedPack = $this->queryRedPack($paySerialno);

  $amount = $RedPack['amount'];
  $number = $RedPack['peopleNum'];
  $type = $RedPack['allotMode'];

  $minMeony = 100;
  $maxMeony = 200;
  $probability= 30;



 $this->allocatioNstrategy($paySerialno,$amount,$number,$type,$minMeony,$maxMeony,$probability);

  }

  public function openRedPack($paySerialno,$uid,$openId,$serial)
  {
  $info=  $this->getRedPackInfo($paySerialno,$serial);

  $record = D('RedPackRecord');

  if($info)
  {
  $Parameter['openid']=	$openId;
  $Parameter['moeny']=$info['moeny'];
  $Parameter['mch_billno']=$info['redPackSerialno'];


  $wxRedPack = A('Mob/WxRedPack');
  $res = $wxRedPack->sendRedpack($Parameter);

  $this->resultRecord($paySerialno,$res);

  if($res['result_code']=='SUCCESS')
  {
  $this->doOpenRedPack($paySerialno,$uid,$serial,2);  //更新状态
  $this->abatementBalance($paySerialno,$Parameter['moeny']);   //执行金额扣减操作

  $record->receiveSucceed($paySerialno,$serial,$uid,$Parameter['moeny'],$info['redPackSerialno'],$res['openid']);
 //  $this->ajaxReturn(array('status'=>0,'info'=>$info['redPackSerialno']));
 return $Parameter['moeny'];

  }else
  {
$record->receiveFailure($paySerialno,$serial,$uid,$res['err_code_des'],$res['openid'],$info['redPackSerialno']);
return false;
  }

  }else
  {

  $record->receiveFailure($paySerialno,$serial,$uid);

  return false;
  }





  }





  public function doOpenRedPack($paySerialno,$uid,$serial,$result)
  {
  	$where = array('paySerialno'=>$paySerialno,'serial'=>$serial,'status'=>1);
  	$data['status']=$result;
  	$data['applyUid']=$uid;
  	$data['applyTime']=getDateTime();
  	$res = M('payment_list')->where($where)->save($data);
  	if($res)
  	{
  	return 	M('payment_list')->where(array('paySerialno'=>$paySerialno,'serial'=>$serial,'status'=>2))->getField('moeny');
  	}else
  	{
  	return null;
  	}



  }
  public function getRedPackInfo ($paySerialno,$serial)
  {
  	$where = array('paySerialno'=>$paySerialno,'serial'=>$serial,'status'=>1);
   return  M('payment_list')->where($where)->field('moeny,redPackSerialno')->find();


  }
  public function closeRedPack($paySerialno)
  {
  $where = array('paySerialno'=>$paySerialno,'releaseStatus'=>1);
  $data['releaseStatus']=3;
  $this->where($where)->save($data);

   $data= array('status'=>4);
   M('payment_list')->where(array('paySerialno'=>$paySerialno,'status'=>'1'))->save($data);
   return true;



  }
  public function getRemainRedPack($paySerialno)
  {

    $Model = new \Think\Model(); // 实例化一个model对象 没有对应任何数据表
  $res = $Model->query("select count(*) as count,FORMAT(sum(moeny)/100,2) as moeny from ocenter_payment_list t where paySerialno = '$paySerialno' and status =1 ");
  return $res[0];


  }

 public function resultRecord($businessId,$contents)
 {
  $data['businessId']=$businessId;
  $data['xmlcontents']=	json_encode($contents);
  $data['type']=1;
   M('payment_result')->add($data);



 }



   protected function ajaxReturn($data, $type = '')
    {
        if (empty($type)) $type = C('DEFAULT_AJAX_RETURN');
        switch (strtoupper($type)) {
            case 'JSON' :
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:application/json; charset=utf-8');
                exit(json_encode($data));
            case 'XML'  :
                // 返回xml格式数据
                header('Content-Type:text/xml; charset=utf-8');
                exit(xml_encode($data));
            case 'JSONP':
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:application/json; charset=utf-8');
                $handler = isset($_GET[C('VAR_JSONP_HANDLER')]) ? $_GET[C('VAR_JSONP_HANDLER')] : C('DEFAULT_JSONP_HANDLER');
                exit($handler . '(' . json_encode($data) . ');');
            case 'EVAL' :
                // 返回可执行的js脚本
                header('Content-Type:text/html; charset=utf-8');
                exit($data);
            default     :
                // 用于扩展其他返回格式数据
                Hook::listen('ajax_return', $data);
        }
    }










}